package edu.uwosh.cs342.group5;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;

public class AsyncPlaceDetails extends AsyncTask<Void, Void, String> {

	String key;
	String ref;
	boolean sensor;
	Context context;

	public AsyncPlaceDetails(String key, String ref, boolean sensor,
			Context context) {
		this.key = key;
		this.ref = ref;
		this.sensor = sensor;
		this.context = context;
	}

	@Override
	protected String doInBackground(Void... params) {

		return PlaceSearch.placeDetails(key, ref, sensor);
	}

	@Override
	protected void onPostExecute(String results) {
		try {
			JSONObject jo = new JSONObject(results).getJSONObject("result");

			SharedPreferences app_preferences = PreferenceManager
					.getDefaultSharedPreferences(context);

			SharedPreferences.Editor editor = app_preferences.edit();
			editor.putString("name", jo.getString("name"));
			
			if (!jo.isNull("rating"))
				editor.putString("rating", jo.getString("rating"));
			else
				editor.putString("rating", "2.5");
			
			if (!jo.isNull("url"))
				editor.putString("url", jo.getString("url"));
			if (!jo.isNull("icon"))
				editor.putString("icon", jo.getString("icon"));
			if (!jo.isNull("website"))
				editor.putString("website", jo.getString("website"));
			if (!jo.isNull("formated_address"))
				editor.putString("formatedAddr",
						jo.getString("formated_address"));
			if (!jo.isNull("formated_phone_number"))
				editor.putString("formatedPhone",
						jo.getString("formated_phone_number"));
			editor.putFloat("lat", (float) jo.getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
			editor.putFloat("lat", (float) jo.getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
			editor.commit();

			Intent ourIntent = new Intent(((GoogleMapsPJ4Activity) context),
					PlaceDetails.class);
			((GoogleMapsPJ4Activity) context).startActivity(ourIntent);

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
